package com.qf.web;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.qf.config.AlipayConfig;
import com.qf.pojo.Order;
import com.qf.service.OrderService;
import com.qf.service.impl.OrderServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/*
*
* 支付宝支付完成之后的回调的控制器
* */
@WebServlet("/aliPayReturnUrlServlet")
public class AliPayReturnUrlServlet extends HttpServlet {


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //支付宝回调 : 外网必须访问:
        //支付宝响应get请求

        PrintWriter out = response.getWriter();
        //获取支付宝GET过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            System.out.println("转码前："+valueStr);
//			valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
//			System.out.println("转码后："+valueStr);
            params.put(name, valueStr);
        }


        try {
            //调用SDK验证签名
            boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type);

            //——请在这里编写您的程序（以下代码仅作参考）——
            if(signVerified) {
                //商户订单号
                String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

                //支付宝交易号
                String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

                //付款金额
                String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");



                //修改订单状态为 已支付
                //调用业务接口,将支付的状态变成1
                OrderService orderService = new OrderServiceImpl() ;
                Order order = orderService.getOrderById(out_trade_no);
                order.setState(1);

                orderService.update(order);

                //重定向
                response.sendRedirect(request.getContextPath()+"/jsp/success.jsp?orderNO="+out_trade_no);
            }else {
                out.println("验签失败");
            }
            //——请在这里编写您的程序（以上代码仅作参考）——
        } catch (AlipayApiException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }
}
